package com.org.platform.utils.wechat;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;

public class WXCore {
    private static final String WATERMARK = "watermark";
    private static final String APPID = "appid";
    /**
     * 解密
     * @param appId   --- 你的appId
     * @param encryptedData --- 加密的数据
     * @param sessionKey --- 密钥（session_key）
     * @param iv
     * @return
     */
    public static String decrypt(String appId, String encryptedData, String sessionKey, String iv){
        String result = "";
        try {
            AES aes = new AES();
            byte[] resultByte = aes.decrypt(Base64.decodeBase64(encryptedData), Base64.decodeBase64(sessionKey), Base64.decodeBase64(iv));
            if(null != resultByte && resultByte.length > 0){
                result = new String(WxPKCS7Encoder.decode(resultByte));
                JSONObject jsonObject = JSONObject.parseObject(result);
                String decryptAppid = jsonObject.getJSONObject(WATERMARK).getString(APPID);
                if(!appId.equals(decryptAppid)){
                    result = "";
                }
            }
        } catch (Exception e) {
            result = "";
            e.printStackTrace();
        }
        return result;
    }
    public static void main(String[] args) throws Exception{
//        https://api.weixin.qq.com/sns/jscode2session?appid=wxac5b3780e06a4ba5&secret=aef318c41442e5135f0526ae1030c922&js_code=071VJoGa1vmyRA0ZZJGa1h2cJB3VJoGn&grant_type=authorization_code
        String appId = "wxac5b3780e06a4ba5";
        String encryptedData = "qjEm0/Bj+9yG/Sqw5cDITG8JgP7WRaiJC7F8Suu9f+ZfECE2Fq2L094U03JJoTiyp1opShGwgd8Vx4HSZMufMiu0dys1DiBl5kQyTuD7iXhuDgJpb/wEkj6gCtLczvHWnMhhupHiUvqe7vtQEC0I/iGQLt3W9qal1xnhHopjiwKRM/lb4StZIeHUCQnmjXTA9ITHRws7tLusUlCrAIcwug==";
        String sessionKey = "YhoRaujlG4wokSjgWAyUiQ==";
        String iv = "mzpBCa1uJWwhIO3T5XA5fw==";
        String result =  decrypt(appId, encryptedData, sessionKey, iv);
        JSONObject jsonObject = JSONObject.parseObject(result);
//防止空指针异常
        if(jsonObject!=null) {
            //获取的该手机号并不一定为非空，所以后面需要判断phone是否为null或者""
            String phone = jsonObject.getString("phoneNumber");
            System.out.println(phone);
        }
    }

}
